import React, { Component } from 'react';
import App from 'layout/App.js'
import CommonModal from './../../components/CommonModal/index.jsx';
import { FormControl, Button, Table, Select, Dropdown, Tree, Icon } from 'tinper-bee';
import { getWorkAdjustProgress,
		 getWorkAdjustProject,
		 searchAdjustHistory,
		 onSearchHistoryList,
		 getUserBaseDataUrl,
		 comparePlanAdjust,
	   } from './workgantt.config.js';
import { vendorsFmtDate, vendorsDanger } from 'utils/config.js';
const Option = Select.Option;
import './index.less';
import Affix from 'bee-affix';
import moment from 'moment';
moment.locale('zh-cn');
let loopData = null;
let GanntPkproject = sessionStorage.getItem('GanntPkproject');
let GanntPkplan = sessionStorage.getItem('GanntPkplan');

import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
const textOverflowIndex = 10; // 控制项目名称在多少个字符后隐藏
import TargetModal from "./../WorkGantt/TargetModal.jsx";
@TargetModal()
export default class PlanApproval extends Component {
	constructor (props){
		super(props);
		this.state ={
			projectList: [],
			projectId: undefined,
			tableData: [],
			projectData: [],
			projectItemArray: [],
			projectKey: undefined,
			showModal: false,
			paramBtnClass: null,
			userName: '',
			historyListData: [],
			modalSize: 'sm',
			modalTitle: '',
			cacheData: {},
			compareCacheData: {},
		}
	}
	componentDidMount () {
		this.init();
		this.getUserBaseData();
	}
	getUserBaseData = () => {
		let _me = this;
		getUserBaseDataUrl({'isAjax': 1, 'ieStamp': new Date().getTime()},
			res=>{
				if (res.data.result !== null) {
					_me.setState({
						userName: res.data.result.userId
					});
				} else {
					_me.setState({
						userName: ''
					});
				}
			},
			error=>{}
			)
	}
	init = () => {
		// 获取项目列表数据
		getWorkAdjustProgress({},
			res => {
				let data = res.data.result.objects;
				if(data.length !== 0){
					this.setState({
						projectList: data
					}, ()=>{
						if(GanntPkproject){
							this.handleSelectChange(GanntPkproject);
							//sessionStorage.setItem('GanntPkproject', undefined);
						}
					});
				}
			},
			error => {}
		)
	}
	handleSelectChange = (value) => {
		// 获取对应的项目进度数据
		getWorkAdjustProject({pkProject: value, ieStamp: new Date().getTime()},
	    	 res => {
	    	 	let data = res.data.result === null ? [] : res.data.result;
	    	 	this.setState({
					projectId: value,
					projectData: data,
					showModal: false
	    	 	}, ()=>{
					let divNode = document.getElementsByClassName('u-select-selection-selected-value')[0]; // 清空下拉框的鼠标hover时候的title值
					setTimeout(() => {
						divNode.setAttribute("title", "");
					}, 500);
					if(GanntPkplan){
						this.handleSelectProjectChange(GanntPkplan);
						//sessionStorage.setItem('GanntPkplan', undefined);
						GanntPkplan = undefined;
					}else{
						this.setState({
							projectKey: undefined
						})
					}
				});
	    	 },
	    	 error => {}
    	 )
	}

	handleSelectProjectChange = (value) => {
		searchAdjustHistory({pkOriginal: value, ieStamp: new Date().getTime()},
	    	 res => {
	    	 	let data = res.data.result === null ? [] : res.data.result;

	    	 	// 计算每项独立数据的进度
	    	 	loopData = data;
	    	 	// this.findMinIndexItem(loopData);

	    	 	this.setState({
					tableData: data,
					projectItemArray: new Array(data.length),
					projectKey: value,
					showModal: false,
					cacheData: {},
					compareCacheData: {},
	    	 	});
	    	 },
	    	 error => {}
    	 )
	}
	findMinIndexItem=(arr)=>{
		arr.forEach((item, index)=>{
			if(item.childCount !== 0){
				this.findMinIndexItem(item.children);
			}else{
				if(item.pkOriginal !== item.pkRoot){
					// 找到最末级并去计算父级的正确progress进度值
					this.computedMinIndexParentItem(arr, item);
				}
			}
		})
	}
	computedMinIndexParentItem=(arr, propsItem)=>{
		let totalDay = 0;
		let totalPresent = 0;
		let currentPresent = 0;
		let tableData = loopData;
		for(let i = 0; i< arr.length; i++){
			let step = 0;
			totalDay+= parseInt(arr[i].expeDuration);
			totalPresent+= parseInt(arr[i].progress) * parseInt(arr[i].expeDuration);
		}
		currentPresent = Math.floor(totalPresent / totalDay);

		// 在树状数据里面找到对应的父级并赋值
		this.recursionDataForParent(tableData, currentPresent, propsItem);

	}
	recursionDataForParent=(tableData, currentPresent, propsItem)=>{
		let tableDataAll = loopData;
		tableData.forEach((item)=>{
			if(item.pkOriginal === propsItem.pkParent){
				item['progress'] = currentPresent;
				// item 为父级 需要往上去递归遍历所以父级
				if(item.pkParent!==null){
					this.findParentItem(tableDataAll, item);
				}
			} else {
				if(item.children !== null){
					this.recursionDataForParent(item.children, currentPresent, propsItem);
				}
			}
		})
	}
	findParentItem=(data, propsItem)=>{
		data.forEach((item)=>{
			if(item.pkOriginal === propsItem.pkParent){
				this.computedMinIndexParentItem(item.children, propsItem);
			} else {
				if(item.children !== null){
					this.findParentItem(item.children, propsItem);
				}
			}
		})
	}
	handlerShowItem = index => {
		this.state.projectItemArray[index] = !this.state.projectItemArray[index];
		this.setState({
			projectItemArray: this.state.projectItemArray,
			showModal: false
		});
	}
	getColumns = (header) => {
		let _me = this;
		function getStatusText(rec) {
			let { changeRecordFlag: flag, version } = rec;
			let text = '';
			let className = '';
			if (header.version == version) {
				switch (flag) {
					case '0':
						text = '修改';
						className = 'modify';
						break;
					case '1':
						text = '新增';
						className = 'new';
						break;
					default:
						return null;
				}
			} else if (flag == '-1') {
				text = '删除';
				className = 'delete';
			} else {
				className = 'old';
				text = 'V' + version;
			}
			return (
				<span className={'version-diff-modify-row ' + className}>{text}</span>
			)
		}
		let columns =  [
		  {
		    title: "计划名称",
		    dataIndex: "name",
			key: "name",
			width: '15%',
		    render(text, rec, index){
		    	return  <p className="clearfix">
							{header.diff && getStatusText(rec)}
							<span>{`${(header.diff && rec.changeRecordFlag == '-1') ? 'V' + rec.version + ' ' : ''}${rec.code}`}</span>
		    				<a href="javascript:;" title={text}>
					    		{text}
					       </a>
		    			</p>
		    }
		  },
		  {
		    title: "工期",
		    dataIndex: "planDays",
		    key: "planDays",
			width: "5%"
		  },
		  {
		    title: "计划开始日期",
		    dataIndex: "planStartDate",
		    key: "planStartDate",
		    width: '8%',
		    render (text, rec, index) {
		    	return <a href="javascript:;">{vendorsFmtDate(text)}</a>
		    }
		  },
		  {
		    title: "计划完成日期",
		    dataIndex: "planEndDate",
		    key: "planEndDate",
		    width: '8%',
		    render (text, rec, index) {
		    	return <a href="javascript:;">{vendorsFmtDate(text)}</a>
		    }
		  },
		  {
		    title: "前置计划",
		    dataIndex: "dependPlanName",
		    key: "dependPlanName",
		    width: '5%'
		  },
		  {
			title: "责任部门",
			dataIndex: "departmentName",
			key: "departmentName",
			width: '5%'
		  },
		  {
		    title: "负责人",
		    dataIndex: "managerName",
		    key: "managerName",
		    width: '5%'
		  },
		  {
			title: "里程碑",
			className: "plan-table-text-center milestone-style",
			width: '18%',
			children: [
				{
				  title: "里程碑档案",
				  dataIndex: "milestoneName",
				  key: "milestoneName",
				  className: "plan-table-text-center",
				  width: '9%',
				  render(text, rec, index) {
					return (
					<span>{text}</span>
					)
				  }
				},
				{
				  title: "里程碑单据",
				  dataIndex: "relatedBillTypeName",
				  key: "relatedBillTypeName",
				  className: "plan-table-text-center",
				  width: '9%',
				  render(text, rec, index) {
					  return (
					  <span>{text}</span>
					  )
				  }
				}
			  ]
		},
		  {
			title: "指标",
			dataIndex: "indexNumber",
			className: "plan-table-text-center",
			key: "indexNumber",
			width: '4%',
			render (text, rec, index) {
				return <a href="javascript:;" onClick={()=>_me.handlerChooseTarget(text, rec, index)} className = {"addTarget"}>
					{rec.childCount === 0 ?text : text? text : ""}
				</a>
			}
		 },
		  {
		    title: "进度",
		    dataIndex: "progressVO.progress",
		    key: "progress",
			width: "5%",
		    render(text, rec, index){
		    	return <a href="javascript:;">{text + '%'}</a>
		    }
		  },
		  {
		    title: "实际开始日期",
		    dataIndex: "progressVO.startDate",
		    key: "actuallyStartDate",
		    width: '8%',
		    render(text, rec, index){
		    	return <a href="javascript:;">{vendorsFmtDate(text)}</a>
		    }
		  },
		  {
		    title: "实际完成日期",
		    dataIndex: "progressVO.endDate",
		    key: "actuallyEndDate",
		    width: '8%',
		    render(text, rec, index){
		    	if(rec.progress === 100){
		    		return <a href="javascript:;">{vendorsFmtDate(text)}</a>
		    	} else {
		    		''
		    	}
		    }
		  },
		  {
			title: "完成人",
			dataIndex: "planFinisherName",
			key: "planFinisherName",
			className: "plan-table-text-center",
			width: '7%',
			render(text, rec, index) {
				return(
					<span>{text}</span>
				)
			}
		   }
		]
		function setColumnsDiff(columns){
			for (let i = 0; i < columns.length; i++) {
				let cur = columns[i];
				if(cur.children){
					setColumnsDiff(cur.children);
					continue;
				}
				if (typeof cur.render !== 'function') {
					cur.render = (text, rec, index) => {
						if (rec.changeRecordFlag === '0') {
							return (<span style={{ color: rec.changeRecords && rec.changeRecords.indexOf(cur.key) != -1 ? 'red' : 'none' }}>{text}</span>);
						} else {
							return text;
						}
					}
				}
				else {
					let temp = cur.render;
					Object.assign(cur, {
						render(text, rec, index) {
							if (rec.changeRecords && rec.changeRecords.indexOf(cur.key) != -1) {
								return (<div className='version-diff-modify-cell'>
									{temp(text, rec, index)}
								</div>);

							} else {
								return temp(text, rec, index);
							}
						}
					})
				}
			}
		}
		if (header.diff) {
			setColumnsDiff(columns);
		}
		return columns;
	}
	setRowClassName = (record, index, indent) => {
		if(record.containDiff){
			return 'row-contain-change';
		}
	}
	handlerChooseTarget = (text, record, index)=>{
		if(text){
			this.props.setCurStateByWrapCom({
				showModal : true,
				from :'browse',
				pkPlan : record.pkOriginal
			})//打开指标列表的模态框
		}
	}
	
	handlerComputedBillStatus = (type, lastFlag) => {
		let billStatusText = '';
		if (type === 1) {
			billStatusText = '生效版';
		} else {
			if (type === 9 && lastFlag === 'N') {
				billStatusText = '历史版';
			} else {
				billStatusText = '编制版';
			}
		}
		return billStatusText
	}
	handlerHistoryList = (item) =>{
		onSearchHistoryList({billType: 'JDJH', tenantId: item.pkTenant, userId: this.state.userName, businessKey: item.pkOriginal, ieStamp: new Date().getTime()},
			res=>{
				if(res.data.resultCode !== 'busi_ex'){
					this.setState({
						showModal: true,
						modalSize: 'lg',
						modalTitle: '审批轨迹',
						modalStatus: 'approvalWay',
						modalConfirmStatus: this.handlerConfirmChooseApporea,
						modalOneBtnStatus: false, 
						chooseItemData: item,
						oneButtonText: '确定',
						paramBtnClass: {'type-1': 'hide', 'type-2': 'hide'},
						historyListData: res.data.result
					});
				}else{
					vendorsDanger({text: res.data.exMsg});
				}
			},
			error=>{

			}
		)
	}
	handlerDeleteClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerComputedContext = () => {
		return <div className="approval--way">
			<div className="way--list">
				<ul>
					{this.state.historyListData.map((item, index)=>{
						return this.handlerCreateListItem(item)
					})}
				</ul>
			</div>
		</div>;
	}
	handlerCreateListItem = (item) => {
		if(item.allApprovalPersonName.indexOf(';') === -1){
			return (<li className="clearfix">
						<div className="item--status">
							<span>{item.approvalStatusDesc}</span>
							{this.handlerComputedClass(item)}
							<b className="line"></b>
						</div>
						<div className="item--content">
							<div className="base--data clearfix">
								<span className="name">{item.allApprovalPersonName}</span>
								<span className="date">{item.approvalRecordVOList[0].endTime}</span>
							</div>
							<p>审批意见：{item.approvalRecordVOList[0].approvalComment}</p>
						</div>
					</li>)
		}else{
			return (<li className="clearfix">
						<div className="item--status">
							<span>{item.approvalStatusDesc}</span>
							{this.handlerComputedClass(item)}
							<b className="line"></b>
						</div>
						<div className="item--content">
							<div className="base--data clearfix">
								<p className="name--spe">{item.allApprovalPersonName.split(';').join('  ')}</p>
							</div>
							<ul className="list--spe">
								{item.approvalRecordVOList.map((item, index)=>{
									return <li>
										<div className="base--data clearfix">
											<span className="name">{item.approvalPersonName}</span>
											<span className="date">{item.endTime}</span>
										</div>
										<p>审批意见：{item.approvalComment}</p>
									</li>
								})}
							</ul>
						</div>
					</li>)
		}
	}
	handlerComputedClass = (item) =>{
		let className = "";
		switch(item.approvalStatus){
			case 'submit':
			case 'adopt':
			className = <em className="right--status"></em>;
			break;
			case 'reject':
			className = <em className='fail--status'></em>;
			break;
			case 'approvalPending':
			className = <em className="pending--status"></em>;
			break;

		}
		return className
	}

	toggleVersionDiff = (item, index, e) => {
		let data = this.state.tableData;

		if (item.diff) {
			this.state.compareCacheData[index] = item;
			data[index] = this.state.cacheData[index];

			this.setState({
				tableData: data
			});
		} else {
			// if (this.state.compareCacheData[index]) {
			// 	data[index] = this.state.compareCacheData[index];
			// 	_me.setState({
			// 		tableData: data,
			// 	});
			// 	return;
			// }
			this.state.cacheData[index] = item;
			let _me = this;
			comparePlanAdjust({ version: item.version, pkSchedule: item.pkSchedule, 'isAjax': 1, 'ieStamp': new Date().getTime() },
				res => {
					if (res.data.result !== null) {
						let rowData = res.data.result;
						rowData.diff = true;
						rowData.scheduleItemVOS.forEach(cur => {
							markContainDiff(cur, item.version);
						});
						data[index] = rowData;
						_me.setState({
							tableData: data,
						});
					}
				},
				error => {
					console.warn(error && error.message);
				}
			)
		}

		function markContainDiff(row, version) {
			if (row.version !== version && row.changeRecordFlag !== '-1') {
				return;
			}
			if (row.children) {
				for (let i = 0; i < row.children.length; i++) {
					let cur = row.children[i];
					markContainDiff(cur, version);
					if (cur.containDiff || cur.changeRecordFlag !== null) {
						row.containDiff = true;
					}
				}
			}
		}

	}
	render (){
		let { projectList, projectItemIndex, projectItemArray, projectData, tableData, defaultSelectKey, projectId, projectKey } = this.state;
		return (
			<App>
				<CommonModal show={this.state.showModal}
                        cancel={this.handlerDeleteClose}
                        confirm={this.handlerDeleteConfirm}
                        hide={this.onhide}
                        content={this.handlerComputedContext()}
                        backdrop={true}
                        paramBtnClass={this.state.paramBtnClass}
                        size={this.state.modalSize}
                        title={this.state.modalTitle}
                        >
           		</CommonModal>

				<Affix>
					<h2 className="title--text">计划版本</h2>
					<div className="header">
						<div className="header__btn--context clearfix">
							<div className="project-select clearfix">
								<p className="project-title">项目:</p>
								<Select
								  size="lg"
								  showSearch
                            	  optionFilterProp="name"
                            	  notFoundContent="没有相关条目"
						          style={{ width: 200, marginRight: 6 }}
						          onChange={this.handleSelectChange}
						          placeholder={'请选择'}
						          value={projectId}
						          disabled={projectList.length === 0 ? true : false}
						        >
						          {
						          	projectList.map((item, index)=>{
										let text = item.sname;
										let displayText = text.length > textOverflowIndex ? text.substr(0, textOverflowIndex) + "..." : text;
										return (
											<Option value={item.pkProject} name={item.sname}>
												<Tooltip
													className={[text.length > textOverflowIndex ? "show" : "hidden"]}
													inverse
													placement="top"
													overlay={text}>
													<div>{displayText}</div>
												</Tooltip>
											</Option>
										)
						          	})
						          }
						        </Select>
							</div>
							<div className="projectName-select clearfix">
								<p className="project-title">计划名称:</p>
								<Select
						          size="lg"
						          style={{ width: 200, marginRight: 6 }}
						          onChange={this.handleSelectProjectChange}
						          placeholder={'请选择'}
						          value={projectKey}
						          disabled={projectData.length === 0 ? true : false}
						        >
						          {
						          	projectData.map((item, index)=>{
						          		return <Option value={item.pkOriginal}>{item.name}</Option>
						          	})
						          }
						        </Select>
							</div>
						</div>
					</div>
				</Affix>
				<div className="project__contain">
				{
					tableData.map((item, index)=>{
						return (<div className="project-item">
									<div className="project-item-header clearfix">
										<i className={ projectItemArray[index] ? 'show-item' : 'close-item'} onClick={()=>{this.handlerShowItem(index)}}></i>
										<p className="item-title">{ index+1 }. {item.name}</p>
										{/* <p className="versio--type">{this.handlerComputedBillStatus(item.billstatus, item.lastFlag)}</p> */}
										<p className="versio--number">版本号：{item.version}</p>
										<p className="create--person">{item.creatorName}</p>
										<p className="create--time">{vendorsFmtDate(item.creationtime)}</p>
										<span className="history--list" onClick={()=>this.handlerHistoryList(item)}></span>
										{
											index != tableData.length - 1 && (
												<span>
													<input type="checkbox" id="versionDiff" checked={item.diff} onClick={this.toggleVersionDiff.bind(null, item, index)} />
													<label className='versionDiff-label' htmlFor='versionDiff'>显示变更记录</label>
												</span>
											)

										}
										<div className="project-item-date clearfix">
											<p className="current-progress">当前进度：{item.progress}%</p>
											<p className="plan-total">计划总工期：{item.planDays}天</p>
											{
												item.expeStartDate !== null && <p className="plan-date">计划日期：{vendorsFmtDate(item.planStartDate)}至{vendorsFmtDate(item.planEndDate)}</p>
											}
											{
												item.startDate !== null && <p className="actual-date">实际日期：{vendorsFmtDate(item.startDate)}至{vendorsFmtDate(item.endDate)}</p>
											}
										</div>
									</div>
									{
										projectItemArray[index] && <div className="project-item-content">
																			<div className="project-table">
																				<Table data={item.scheduleItemVOS === null ? [] : item.scheduleItemVOS} columns={this.getColumns(item)}
																					rowClassName = {this.setRowClassName}
																				></Table>
																			</div>
																		</div>
									}
								</div>)
					})
				}
				</div>
			</App>
			)
	}
}